#include <iostream>
#include <unistd.h>
#include <pthread.h>

// pthread_join调用结束
void *thread1(void *argv)
{
    int cut1 = 10;
    while (cut1)
    {
        std::cout << "child thread pid: " << getpid() << argv << std::endl;
        cut1--;
        sleep(1);
    }
    return (void *)100;
}

// 线程自己终止
void *thread2(void *argv)
{
    sleep(15);
    pthread_exit(0);
}

// 主线程终止
void *thread3(void *argv)
{
    sleep(100);
    return NULL;
}

// 线程自己分离
void *thread4(void *argv)
{
    pthread_detach(pthread_self());
    sleep(25);
    return NULL;
}

// 主线程分离
void *thread5(void *argv)
{
    sleep(30);
    return NULL;
}

void Linux_pthread()
{
    // pthread_join调用结束
    pthread_t pth1_id;
    int pth1_ret = pthread_create(&pth1_id, NULL, thread1, (void *)"thread1_name");
    // 线程自己终止
    pthread_t pth2_id;
    int pth2_ret = pthread_create(&pth2_id, NULL, thread2, (void *)"thread2_name");
    // 主线程终止
    pthread_t pth3_id;
    int pth3_ret = pthread_create(&pth3_id, NULL, thread3, (void *)"thread3_name");
    // 线程自己分离
    pthread_t pth4_id;
    int pth4_ret = pthread_create(&pth4_id, NULL, thread4, (void *)"thread4_name");
    // 主线程分离
    pthread_t pth5_id;
    int pth5_ret = pthread_create(&pth5_id, NULL, thread5, (void *)"thread5_name");

    pthread_detach(pth5_id);

    sleep(20);
    pthread_cancel(pth3_id);

    sleep(15);

    void *ch1;
    // 等待进程
    pthread_join(pth1_id, &ch1);
}

#include <thread>

void threadcpp()
{
    int cut1 = 10;
    while (cut1)
    {
        std::cout << "child cpp thread pid: " << getpid() << std::endl;
        cut1--;
        sleep(1);
    }
}

int main()
{
    // linux线程
    // Linux_pthread();

    // c++线程
    std::thread myth(threadcpp);

    int cut1 = 10;
    while (cut1)
    {
        std::cout << "parent cpp thread pid: " << getpid() << std::endl;
        cut1--;
        sleep(1);
    }

    myth.join();

    return 0;
}
